package com.zz.servlet3.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;

@MultipartConfig
@WebServlet(urlPatterns = "/upload")
public class MulitpartServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("file");
        PrintWriter out = resp.getWriter();
        out.println("file size: " + part.getSize() + "\r\n");
        out.println("file type: " + part.getContentType() + "\r\n");
        out.println("file type: " + getFileType(part) + "\r\n");
        out.println("file name: " + getFileName(part) + "\r\n");
    }

    private String getFileType(Part p) {
        String name = p.getHeader("content-disposition");
        String fileNameTmp = name.substring(name.indexOf("filename=") + 10);
        return fileNameTmp.substring(fileNameTmp.indexOf(".") + 1, fileNameTmp.indexOf("\""));
    }

    private String getFileName(Part p) {
        String name = p.getHeader("content-disposition");
        String fileNameTmp = name.substring(name.indexOf("filename=") + 10);
        return fileNameTmp.substring(0, fileNameTmp.indexOf("\""));
    }

}
